// @ts-nocheck

import router from '@/middleware/router'
import { JsonDB } from '@/utils/JsonDB'
import crypto from 'crypto'
import fs from 'fs'
import mineTypes from 'mime-types'
import path from 'path'

const dataJSON = path.join(__dirname, '../assets/data.json')
const db = new JsonDB(dataJSON)

function classifyByMime(mimeType) {

  if (mimeType.startsWith('text/')) return 'file'
  if (mimeType.startsWith('audio/')) return 'audio'
  if (mimeType.startsWith('video/')) return 'video'
  if (mimeType.startsWith('image/')) return 'image'
  return 'file'
}


const PREFIX = '/message'
router.get(`${PREFIX}/getAllMsg`, (ctx) => {
  const data = db.get('message')


  ctx.body = { code: 200, msg: '请求成功', data }
})

router.post(`${PREFIX}/clearMsg`, (ctx) => {
  db.delete('message')
  db.set('message', [])


  ctx.body = { code: 200, msg: '删除成功', data: {} }
})


router.post(`${PREFIX}/sendText`, (ctx) => {
  const { text } = ctx.request.body
  const timestamp = new Date().toISOString()
  const data = {
    timestamp,
    content: {
      type: "text",
      text: text
    }
  }

  console.log(data)
  db.addAsync('message', data)

  ctx.body = { code: 200, msg: '发送成功', data }
})

router.post(`${PREFIX}/sendFile`, (ctx) => {

  const file = ctx.request.files.file
  const originalFilename = file.originalFilename

  const timestamp = new Date().toISOString()

  let mimeType = mineTypes.lookup(originalFilename)
  if (mimeType.endsWith('mp4')) {
    mimeType = 'video/mp4'
  }
  const fileType = classifyByMime(mimeType)
  const data = {
    timestamp,
    content: {
      type: fileType,
      url: ''
    }
  }


  // 获取文件扩展名
  const ext = path.extname(originalFilename)

  // 生成随机文件名（使用时间戳+随机数）
  const randomName = `${Date.now()}-${Math.floor(Math.random() * 10000)}${ext}`

  const uploadPath = path.join(__dirname, '../upload')

  // 创建上传目录（如果不存在）
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true })
  }

  const filePath = path.join(uploadPath, randomName)

  return new Promise((resolve, reject) => {
    const reader = fs.createReadStream(file.filepath)
    const upStream = fs.createWriteStream(filePath)

    upStream.on('finish', () => {
      const buf = fs.readFileSync(filePath)
      const hash = crypto.createHash('md5').update(buf).digest('hex')
      resolve({
        md5: hash,
        filename: randomName,
        originalFilename: originalFilename
      })
    })

    upStream.on('error', (err) => {
      reject(err)
    })

    reader.pipe(upStream)


    data.content.url = `/upload/${randomName}`
    db.addAsync('message', data)

    ctx.body = {
      code: 200,
      msg: "上传成功",
      data
    }
  })
})